#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define CPORT  10086
#define SPORT  10010
#define IP     "127.0.0.1"
#define SIZE   100

//tcp服务器

int main()
{
	int socketID = 0;
	struct sockaddr_in addr;
	int addrLength = 0;
	char buf[SIZE] = {0};
	int newID = 0;
	
	// 创建套接字描述符(协议)
	socketID = socket( PF_INET, SOCK_STREAM, 0 );
	if ( 0 > socketID )
	{
		perror("socket error");
		return -1;
	}	
	
    // 绑定自己的地址(ip+port)
	addrLength = sizeof(addr);
	memset(&addr, 0, addrLength);
	addr.sin_family = PF_INET;
	addr.sin_port = htons(SPORT);
	addr.sin_addr.s_addr = INADDR_ANY;
	if ( 0 > bind(socketID, (struct sockaddr *)&addr, addrLength ) )
	{
		perror("bind error");
		goto ERROR;
	}
	printf("server bind ok\r\n");
    // 建立监听	
	if ( 0 > listen(socketID, 10) )
	{
		perror("listen error");
		goto ERROR;
	}
	printf("server listen ok\r\nserver waiting for connect ......\r\n");	
	
    // 接受连接
	newID = accept( socketID, (struct sockaddr *)&addr, &addrLength );
	if ( 0 > newID )
	{
		perror("accept error");
		goto ERROR;
	}
	
    // 通信 
	if ( 0 > read(newID, buf, SIZE - 1))
	{
		perror("recv msg error");
	}
	else 
	{
		printf("server get msg , msg:%s\r\n", buf);
	}
    // 关闭套接字描述符
	close(newID);
	close(socketID);
	return 0;

ERROR:
	
	close(socketID);
	return -1;
}